﻿using System;
using System.IO.Ports;

namespace ConsoleDemo
{
    internal class SerialPortExample
    {
        private static SerialPort _serialPort;

        public static void Test()
        {
            // 1. 初始化串口参数
            _serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);

            // 2. 注册数据接收事件
            _serialPort.DataReceived += DataReceivedHandler;

            try
            {
                // 3. 打开串口
                _serialPort.Open();
                Console.WriteLine("串口已打开，输入消息按回车发送(输入exit退出):");

                // 4. 发送数据循环
                while (true)
                {
                    string input = Console.ReadLine();
                    if (input.ToLower() == "exit") break;

                    _serialPort.WriteLine(input);
                    Console.WriteLine($"已发送: {input}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
            finally
            {
                // 5. 关闭串口
                if (_serialPort.IsOpen)
                    _serialPort.Close();
            }
        }

        // 数据接收处理方法
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string receivedData = sp.ReadExisting();
            Console.WriteLine($"收到数据: {receivedData}");
        }
    }
}
